import React, { useState } from 'react';
import { UserPlusIcon, AcademicCapIcon, UserIcon, LockClosedIcon } from '@heroicons/react/24/outline';

const Register = () => {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    studentId: '',
    verificationCode: ''
  });
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [isCodeSent, setIsCodeSent] = useState(false);
  const [codeCountdown, setCodeCountdown] = useState(0);

  const validateForm = (): boolean => {
    const newErrors = {};

    if (!formData.username.trim()) {
      newErrors.username = '用户名不能为空';
    }

    if (!formData.studentId.trim()) {
      newErrors.studentId = '学号不能为空';
    } else if (!/^\d{10,12}$/.test(formData.studentId)) {
      newErrors.studentId = '请输入有效的学号（10-12位数字）';
    }

    if (!formData.verificationCode.trim()) {
      newErrors.verificationCode = '验证码不能为空';
    } else if (!/^\d{6}$/.test(formData.verificationCode)) {
      newErrors.verificationCode = '请输入6位数字验证码';
    }

    if (!formData.password) {
      newErrors.password = '密码不能为空';
    } else if (formData.password.length < 6) {
      newErrors.password = '密码长度至少6位';
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSendCode = () => {
    if (!formData.studentId.trim()) {
      setErrors({ studentId: '请先输入学号' });
      return;
    }

    if (!/^\d{10,12}$/.test(formData.studentId)) {
      setErrors({ studentId: '请输入有效的学号（10-12位数字）' });
      return;
    }

    // 模拟发送验证码
    setIsCodeSent(true);
    setCodeCountdown(60);
    
    // 倒计时
    const timer = setInterval(() => {
      setCodeCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    alert('验证码已发送到您的学号关联邮箱，请查收！');
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      // 这里应该调用实际的注册API
      console.log('注册数据:', formData);
      
      // 模拟注册成功
      alert('注册成功！请使用学号和密码登录。');
      
      // 重置表单
      setFormData({
        username: '',
        password: '',
        confirmPassword: '',
        studentId: '',
        verificationCode: ''
      });
      setIsCodeSent(false);
      setCodeCountdown(0);
    } catch (error) {
      setErrors({ general: '注册失败，请稍后重试' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <div className="flex justify-center">
          <div className="w-20 h-20 bg-primary rounded-full flex items-center justify-center">
            <UserPlusIcon className="w-10 h-10 text-white" />
          </div>
        </div>
        <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
          学生注册
        </h2>
        <p className="mt-2 text-center text-sm text-gray-600">
          创建您的健身房账户
        </p>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
          <form className="space-y-6" onSubmit={handleSubmit}>
            {/* 学号 */}
            <div>
              <label htmlFor="studentId" className="block text-sm font-medium text-gray-700">
                学号 *
              </label>
              <div className="mt-1 relative">
                <input
                  id="studentId"
                  name="studentId"
                  type="text"
                  required
                  value={formData.studentId}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="请输入学号"
                />
                <AcademicCapIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.studentId && (
                <p className="mt-1 text-sm text-red-600">{errors.studentId}</p>
              )}
            </div>

            {/* 学号验证码 */}
            <div>
              <label htmlFor="verificationCode" className="block text-sm font-medium text-gray-700">
                学号验证码 *
              </label>
              <div className="mt-1 flex gap-2">
                <div className="flex-1 relative">
                  <input
                    id="verificationCode"
                    name="verificationCode"
                    type="text"
                    required
                    value={formData.verificationCode}
                    onChange={handleInputChange}
                    className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                    placeholder="请输入6位验证码"
                    maxLength={6}
                  />
                </div>
                <button
                  type="button"
                  onClick={handleSendCode}
                  disabled={codeCountdown > 0}
                  className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                    codeCountdown > 0
                      ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                      : 'bg-primary text-white hover:bg-primary-300'
                  }`}
                >
                  {codeCountdown > 0 ? `${codeCountdown}s` : '发送验证码'}
                </button>
              </div>
              {errors.verificationCode && (
                <p className="mt-1 text-sm text-red-600">{errors.verificationCode}</p>
              )}
            </div>

            {/* 用户名 */}
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-gray-700">
                用户名 *
              </label>
              <div className="mt-1 relative">
                <input
                  id="username"
                  name="username"
                  type="text"
                  required
                  value={formData.username}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="请输入用户名"
                />
                <UserIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.username && (
                <p className="mt-1 text-sm text-red-600">{errors.username}</p>
              )}
            </div>

            {/* 密码 */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                密码 *
              </label>
              <div className="mt-1 relative">
                <input
                  id="password"
                  name="password"
                  type="password"
                  required
                  value={formData.password}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="请输入密码（至少6位）"
                />
                <LockClosedIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.password && (
                <p className="mt-1 text-sm text-red-600">{errors.password}</p>
              )}
            </div>

            {/* 确认密码 */}
            <div>
              <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
                确认密码 *
              </label>
              <div className="mt-1 relative">
                <input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  required
                  value={formData.confirmPassword}
                  onChange={handleInputChange}
                  className="appearance-none block w-full px-3 py-2 pl-10 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                  placeholder="请再次输入密码"
                />
                <LockClosedIcon className="w-5 h-5 text-gray-400 absolute left-3 top-2.5" />
              </div>
              {errors.confirmPassword && (
                <p className="mt-1 text-sm text-red-600">{errors.confirmPassword}</p>
              )}
            </div>

            {errors.general && (
              <div className="bg-red-50 border border-red-200 rounded-md p-3">
                <p className="text-sm text-red-600">{errors.general}</p>
              </div>
            )}

            <div>
              <button
                type="submit"
                disabled={isLoading}
                className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading ? '注册中...' : '注册'}
              </button>
            </div>

            <div className="text-center">
              <p className="text-sm text-gray-600">
                已有账户？{' '}
                <a href="/login" className="font-medium text-primary hover:text-primary-300">
                  立即登录
                </a>
              </p>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Register; 